package com.acegear.horizon.domain.services;

import com.mashape.unirest.http.Unirest;
import com.mashape.unirest.http.exceptions.UnirestException;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.Optional;

import redis.clients.jedis.Jedis;

/**
 * Created by wangsike on 2017/2/18.
 */
@Service
public class SSOService {
    @Value("${sso.wx.pub.id}")
    private String wxPubId;

    @Value("${sso.wx.pub.secret}")
    private String wxPubSecret;

    @Value("${sso.wx.app.id}")
    private String wxAppId;

    @Value("${sso.wx.app.secret}")
    private String wxAPpSecret;

    @Value("${sso.wx.url}")
    private String wxUrl;

    @Value("${sso.wb.id}")
    private String wbAppId;

    @Value("${sso.wb.secret}")
    private String wbSecret;

    @Value("${sso.wb.url}")
    private String wbUrl;

    @Autowired
    private Jedis jedis;

    private void saveCode(String code) {
        jedis.set(code, "");
        jedis.expire(code, 60);
    }

    private boolean existCode(String code) {
        return jedis.exists(code);
    }

    public Optional<WxSSOResponse> wxPubAccessToken(String code, Integer type) {
        try {
            if (!existCode(code)) {
                saveCode(code);
                String url;
                if (type == 1) {
                    //app
                    url = String.format(wxUrl, wxAppId, wxAPpSecret, code);
                } else {
                    //pub
                    url = String.format(wxUrl, wxPubId, wxPubSecret, code);
                }
                WxSSOResponse response = Unirest
                        .get(url)
                        .asObject(WxSSOResponse.class)
                        .getBody();

                if (response.isError()) {
                    return Optional.empty();
                } else {
                    return Optional.of(response);
                }
            } else {
                return Optional.empty();
            }
        } catch (UnirestException e) {
            e.printStackTrace();
            return Optional.empty();
        }
    }

    public Optional<WbSSOResponse> wbAccessToken(String code) {
        try {
            if (!existCode(code)) {
                saveCode(code);
                String url = String.format(wbUrl, wbAppId, wbSecret, code);
                WbSSOResponse response = Unirest
                        .get(url)
                        .asObject(WbSSOResponse.class)
                        .getBody();
                if (response.isError()) {
                    return Optional.empty();
                } else {
                    return Optional.of(response);
                }
            } else {
                return Optional.empty();
            }
        } catch (UnirestException e) {
            e.printStackTrace();
            return Optional.empty();
        }
    }
}